<template>
  <view class="page-wrapper">
    <nav-bar title="扫码12314"></nav-bar>

    <!-- 主体显示区域 -->
    <view class="page-main">
      <button @click="plus_scan_1">开始扫描</button>
    </view>
  </view>
</template>

<script setup>
// import { ref, onMounted, onBeforeUnmount, reactive } from 'vue';
import utils from '@/common/js/utils/index.js';

const scanBox = ref(null);

const info = reactive({
  scanInstance_1: null,
});

const plus_scan_1 = () => {
  try {
    if (info.scanInstance_1) {
      closeScan_1();
    }

    info.scanInstance_1 = plus.barcode.create(
      'barcode',
      [plus.barcode.QR],
      {
        top: '0px',
        left: '0px',
        width: '100%',
        height: '100%',
        position: 'static',
      },
      true
    );
    info.scanInstance_1.onmarked = function (type, result) {
      console.log('Success: type=' + type + ', result=' + result);
      if (result) {
        scanLogin({
          usercode: result.split(',')[0],
          password: result.split(',')[1],
        });
      } else {
        uni.showToast({
          title: '扫码失败，请重试！',
          icon: 'none',
        });
      }
      closeScan_1();
    };
    info.scanInstance_1.onerror = function (type, result) {
      closeScan_1();
    };
    plus.webview.currentWebview().append(info.scanInstance_1);
    info.scanInstance_1.start();
    console.log(58, '开始扫描');
  } catch (err) {
    console.log('扫码--plus.barcode.create', err);
  }
};

const closePage = () => {
  uni.navigateBack({
    delta: 1, // 返回到上一个页面
  });
};

const closeScan_1 = () => {
  if (info.scanInstance_1) {
    info.scanInstance_1.close();
    info.scanInstance_1 = null;
  }
};

const errorCallback = (error) => {
  uni.showToast({
    title: '扫码失败，请重试',
    icon: 'error',
  });
  uni.navigateBack({
    delta: 1, // 返回到上一个页面
  });
};

const plusScan = () => {
  let scan = null;
  //扫码成功回调
  function onmarked(type, result) {
    scan.close(); //结束视频捕获

    uni.navigateBack({
      delta: 1, // 返回到上一个页面
      success: () => {
        eventChannel.emit('scansuccess', {
          from: 'plusscan',
          msg: {
            type,
            result,
          },
        });
      },
    });
  }

  try {
    var filter = [plus.barcode.QR];
    //自定义的扫描控件样式
    var styles = {
      top: '0px',
      left: '0px',
      width: '100%',
      height: '100%',
      position: 'static',

      frameColor: '#ffffff',
      scanbarColor: '#ffffff',
      background: '',
    };
    info.scanInstance_1 = new plus.barcode.Barcode(
      'scanarea',
      filter,
      styles,
      true
    );
    info.scanInstance_1.onmarked = onmarked;
    info.scanInstance_1.onerror = errorCallback;
    info.scanInstance_1.start(); //开始扫码
  } catch (err) {
    errorCallback(); // 返回上一个页面并关闭
  }
};

onMounted(() => {
  // plusScan();
  // plus_scan_1();
});

onBeforeUnmount(() => {
  // closeScan();
});
</script>

<style lang="scss" scoped></style>
